/*
 * =====================================================================================
 *
 *       Filename:  physicshandler.cpp
 *
 *    Description:  cpp file to handle all phsyics interactions
 *
 *        Version:  1.0
 *        Created:  Monday 22 November 2010 08:04:47  IST
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  shashank singh 
 *        Company:  Awaaz.me
 *
 * =====================================================================================
 */

#include "physicshandler.h"

physicsHandler::physicsHandler()
{
doSleep =true;
gravity= new b2Vec2(0.0f, -10.0f);
world=new b2World(*gravity, doSleep);
groundBodyDef= new b2BodyDef;
groundBodyDef->position.Set(0.0f,-10.0f);
groundBody=world->CreateBody(groundBodyDef);
groundBox=new b2PolygonShape;
groundBox->SetAsBox(50.0f, 10.0f);
groundBody->CreateFixture(groundBox, 0.0f);
timeStep=1.0f/6.0f;
velocityIterations=6;
positionIterations=2;
conversionRatioFrombox2dToScreen=320/10;//screenresolution/world size
conversionRatioFromScreenTobox2d=320/10;
addBody();
}

physicsHandler::~physicsHandler()
{
delete world;//this automatically frees up all pointers realted to this world , but do set all pointers to null
}

int physicsHandler::convertToScreenResolution(float32)
{
return (int)0; 
}

float32 physicsHandler::convertFromScreenResolution(int)
{
return (float32)0;
}

void physicsHandler::simulate()
{
world->Step(timeStep,velocityIterations,positionIterations);
world->ClearForces();
  
b2Vec2 position = body->GetPosition();
float32 angle = body->GetAngle();
//qDebug()<<__PRETTY_FUNCTION__;
printf("%4.2f,%4.2f,%4.2f\n",position.x,position.y,angle);
emit move(position.x/10,-position.y/10);
}


void physicsHandler::addBody()
{
bodyDef =new b2BodyDef;
dynamicBox =new b2PolygonShape;
fixtureDef =new b2FixtureDef;
bodyDef->type = b2_dynamicBody;
bodyDef->position.Set(0.0f, 0.0f);
body = world->CreateBody(bodyDef);
dynamicBox->SetAsBox(1.0f, 1.0f);
fixtureDef->shape = dynamicBox;
fixtureDef->density = 1.0f;
fixtureDef->friction = 0.3f;
body->CreateFixture(fixtureDef);
}
